'use client'

import {
  createContext,
  useContext,
  useState,
  ReactNode,
  Dispatch,
  SetStateAction,
} from "react"
import { Content } from "@/types/content"
import { ChatMessage } from "@/types/fetch"

interface ChatContextType {
  messages: ChatMessage[]
  setMessages: Dispatch<SetStateAction<ChatMessage[]>>
  isGenerating: boolean
  setIsGenerating: Dispatch<SetStateAction<boolean>>
  currentChatId: string | null
  setCurrentChatId: Dispatch<SetStateAction<string | null>>
  contentDetail: Content | null
  setContentDetail: Dispatch<SetStateAction<Content | null>>
}

const ChatContext = createContext<ChatContextType | undefined>(undefined)

export function ChatProvider({ children }: { children: ReactNode }) {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [isGenerating, setIsGenerating] = useState(false)
  const [currentChatId, setCurrentChatId] = useState<string | null>(null)
  const [contentDetail, setContentDetail] = useState<Content | null>(null)

  return (
    <ChatContext.Provider
      value={{
        messages,
        setMessages,
        isGenerating,
        setIsGenerating,
        currentChatId,
        setCurrentChatId,
        contentDetail,
        setContentDetail,
      }}
    >
      {children}
    </ChatContext.Provider>
  )
}

export function useChatContext() {
  const context = useContext(ChatContext)
  if (context === undefined) {
    throw new Error("useChatContext must be used within a ChatProvider")
  }
  return context
}